package org.liziing.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.liziing.shortlink.admin.common.biz.user.UserContext;
import org.liziing.shortlink.admin.common.convention.exception.ClientException;
import org.liziing.shortlink.admin.common.convention.result.Result;
import org.liziing.shortlink.admin.common.database.BaseDO;
import org.liziing.shortlink.admin.dao.entity.GroupDO;
import org.liziing.shortlink.admin.dao.mapper.GroupMapper;
import org.liziing.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import org.liziing.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import org.liziing.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import org.liziing.shortlink.admin.remote.ShortLinkServiceActualRemoteService;
import org.liziing.shortlink.admin.remote.dto.resp.ShortLinkGroupQueryRespDTO;
import org.liziing.shortlink.admin.service.GroupService;
import org.liziing.shortlink.admin.toolkit.RandomGenerator;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import static org.liziing.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final ShortLinkServiceActualRemoteService shortLinkServiceActualRemoteService;
    private final RedissonClient redissonClient;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(String name) {
        if (name.equals("默认分组")) {
            return;
        }
        saveGroup(UserContext.getUsername(), name);
    }
    @Override
    public void saveGroup(String username,String name) {
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum) {
                throw new ClientException(String.format("分组数量达到上线 %d", groupMaxNum));
            }
            String gid = "";
            do {
                gid = RandomGenerator.generateRandomString();
            } while (!hasCheck(username, gid));

            GroupDO groupDO = GroupDO.builder()
                    .gid(gid)
                    .name(name)
                    //TODO 获取当前用户名
                    .username(username)
                    .sortOrder(0)
                    .build();
            baseMapper.insert(groupDO);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder)
                .orderByDesc(BaseDO::getUpdateTime);
        List<GroupDO> groupDOS = baseMapper.selectList(queryWrapper);
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOS = BeanUtil.copyToList(groupDOS, ShortLinkGroupRespDTO.class);

        Result<List<ShortLinkGroupQueryRespDTO>> linkQueryCount =
                shortLinkServiceActualRemoteService.shortLinkQueryCount(groupDOS.stream().map(GroupDO::getGid).toList());

        shortLinkGroupRespDTOS.forEach(each -> {
            Optional<ShortLinkGroupQueryRespDTO> first = linkQueryCount.getData().stream()
                    .filter(item -> each.getGid().equals(item.getGid()))
                    .findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOS;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO1 = baseMapper.selectOne(eq);
        if ((groupDO1.getName()).equals("默认分组")) {
            return;
        }
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);


        GroupDO groupDO = GroupDO.builder()
                .name(requestParam.getName())
                .build();
        baseMapper.update(groupDO, updateWrapper);
    }

    @Override
    public void deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = baseMapper.selectOne(updateWrapper);
        if ((groupDO.getName()).equals("默认分组")) {
            return;
        }
//        GroupDO groupDO = new GroupDO();
//        groupDO.setDelFlag(1);
        baseMapper.delete(updateWrapper);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();

            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO, updateWrapper);
        });
    }


    public boolean hasCheck(String username, String gid) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, username);
        GroupDO groupDO = baseMapper.selectOne(queryWrapper);
        return groupDO == null;
    }
}
